﻿using System;
using System.Windows.Threading;
using MvvmFx.Common.ViewModels;
using MvvmFx.Common.ViewModels.Commands;
using Pomodoro.ViewModels.Models;

namespace Pomodoro.ViewModels
{
    public class AppViewModel : ViewModelBase
    {
        private SelectableCollection<PersonViewModel> personViewModels;
        private readonly DelegateCommand addPerson;
        private readonly DelegateCommand removePerson;

        public AppViewModel()
        {
            this.addPerson = new DelegateCommand(OnAddPersonExecuted);
            this.removePerson = new DelegateCommand(OnRemovePersonExecuted);
        }
    
        public void Startup()
        {
            this.personViewModels = PersonsLoader.Load();
        }

        public void Exit()
        {
          //  DataService.SaveTasks();
        }

        /// <summary>
        /// Gets the value of the <see cref=”PersonViewModels”/> property.
        /// </summary>
        public SelectableCollection<PersonViewModel> PersonViewModels
        {
            get { return personViewModels; }
        }

        /// <summary>
        /// Gets the value of the <see cref=”AddPerson”/> property.
        /// </summary>
        public DelegateCommand AddPerson
        {
            get { return addPerson; }
        }

        private void OnAddPersonExecuted()
        {
            var newPersonVM = new PersonViewModel()
                                  {
                                      Name = "New Person",
                                      Photo = @"/Pomodoro.Oob;Component/Images/NewPerson.png",
                                      Role = "Developer",
                                  };

            this.personViewModels.Add(newPersonVM);

            newPersonVM.IsSelected = true;
        }

        /// <summary>
        /// Gets the value of the <see cref=”AddPerson”/> property.
        /// </summary>
        public DelegateCommand RemovePerson
        {
            get { return removePerson; }
        }

        private void OnRemovePersonExecuted()
        {
            if(this.personViewModels.HasSelectedItem)
            {
                int index = this.personViewModels.IndexOf(this.personViewModels.SelectedItem);

                this.personViewModels.Remove(this.personViewModels.SelectedItem);

                index = Math.Max(0, --index);
                if(this.personViewModels.Count > index)
                {
                    this.personViewModels[index].IsSelected = true;
                }
            }
        }
    }
}
